/* eslint-disable */
import React, { useState, useEffect } from 'react';
import { Upload, Button, message, Progress, Row, Col, Input, Card, Typography, Spin, Menu, Anchor } from 'antd';
import { UploadOutlined, VideoCameraOutlined, HistoryOutlined } from '@ant-design/icons';
import axios from 'axios';
import OSS from 'ali-oss';

const { Title } = Typography;
const CHUNK_SIZE = 5 * 1024 * 1024; // 5MB

const Publish = () => {
  const [fileList, setFileList] = useState([]);
  const [uploading, setUploading] = useState(false);
  const [progress, setProgress] = useState({});
  const [videoPreviews, setVideoPreviews] = useState({});
  const [uploadedFiles, setUploadedFiles] = useState([]);
  const [loading, setLoading] = useState(false);
  const [currentTab, setCurrentTab] = useState('upload');

  useEffect(() => {
    fetchUploadedFiles();
  }, []);

  const fetchUploadedFiles = async () => {
    setLoading(true);
    try {
      const authToken = localStorage.getItem('token');
      if (!authToken) {
        throw new Error('JWT token not found');
      }

      const response = await axios.get('http://47.111.104.30:8080/api/tasks/uploaded-files', {
        headers: {
          'Authorization': `Bearer ${authToken}`,
        },
      });
      setUploadedFiles(response.data);
    } catch (error) {
      message.error('获取上传文件列表失败');
    } finally {
      setLoading(false);
    }
  };

  const generateSignedUrl = (fileName) => {
    const client = new OSS({
      region: 'oss-cn-chengdu',
      accessKeyId: 'LTAI5tAtRHAntQwrD5tqpkYh',
      accessKeySecret: 'SaRcRBQXT3ZLNGgf4RDvXLYPDxKGet',
      bucket: 'upload-mental-health',
    });

    return client.signatureUrl(fileName, { expires: 3600 });
  };

  const handleUpload = async () => {
    if (fileList.length === 0) {
      message.error('请先选择需要上传的文件');
      return;
    }

    const handleAnchorClick = (key) => {
      setCurrentTab(key);
    };

    setUploading(true);
    let allUploadSuccess = true;

    const uploadFile = async (file) => {
      const totalChunks = Math.ceil(file.size / CHUNK_SIZE);
      let uploadedChunks = 0;

      for (let start = 0; start < file.size; start += CHUNK_SIZE) {
        const chunk = file.slice(start, start + CHUNK_SIZE);
        const formData = new FormData();
        formData.append('file', chunk);
        formData.append('filename', file.name);
        formData.append('chunkIndex', Math.floor(start / CHUNK_SIZE));
        formData.append('totalChunks', totalChunks);

        try {
          const authToken = localStorage.getItem('token');
          if (!authToken) {
            throw new Error('JWT token not found');
          }

          await axios.post('http://localhost:8080/api/tasks/upload', formData, {
            headers: {
              'Content-Type': 'multipart/form-data',
              'Authorization': `Bearer ${authToken}`,
            },
          });
          uploadedChunks += 1;
          setProgress((prevProgress) => ({
            ...prevProgress,
            [file.name]: Math.round((uploadedChunks / totalChunks) * 100),
          }));
        } catch (error) {
          message.error(`文件上传失败: ${file.name}`);
          allUploadSuccess = false;
          break;
        }
      }

      if (allUploadSuccess) {
        setUploadedFiles((prevFiles) => [...prevFiles, file.name]);
        fetchUploadedFiles(); // 更新上传文件列表
      }
    };

    await Promise.all(fileList.map(uploadFile));

    setUploading(false);
    if (allUploadSuccess) {
      message.success('文件上传成功');
    }
  };

  const handleRemove = (file) => {
    setFileList((prevFileList) => prevFileList.filter((item) => item.uid !== file.uid));
    setVideoPreviews((prevPreviews) => {
      const { [file.uid]: _, ...rest } = prevPreviews;
      return rest;
    });
  };

  const handleBeforeUpload = (file) => {
    if (!file.type.match('video.*')) {
      message.error('只能上传视频文件');
      return false;
    }
    setFileList((prevFileList) => [...prevFileList, file]);
    setVideoPreviews((prevPreviews) => ({
      ...prevPreviews,
      [file.uid]: URL.createObjectURL(file),
    }));
    return false;
  };

  return (
    <div style={{ display: 'flex', minHeight: '100vh', backgroundColor: '#f0f2f5' }}>
      {/* 左侧导航栏 */}
      <div style={{ width: '200px', backgroundColor: '#ffffff', padding: '20px 0', marginTop: '25px', marginLeft: '20px',height: '945px' }}>
  <div style={{ padding: '20px', textAlign: 'center' }}>
  </div>
  <Menu
    theme="light"
    mode="inline"
    style={{ height: '100%', borderRight: 0 }}
    selectedKeys={[currentTab]}
    onClick={({ key }) => setCurrentTab(key)}
    items={[
      {
        key: 'upload',
        icon: <UploadOutlined />,
        label: '上传视频',
      },
      {
        key: 'history',
        icon: <HistoryOutlined />,
        label: '上传记录',
      },
    ]}
    itemStyle={{
      // 悬停时的背景颜色
      ':hover': {
        backgroundColor: '#f0f0f0',
      },
      // 选中时的背景颜色
      backgroundColor: currentTab === 'upload' ? '#e6f7ff' : 'transparent',
    }}
    selectedKeysStyle={{
      backgroundColor: '#e6f7ff',
    }}
  />
</div>

      {/* 主内容区域 */}
      <div style={{ flex: 1, padding: '24px', overflowY: 'auto' }}>
        {currentTab === 'upload' ? (
          <Card
            title={
              <div style={{ display: 'flex', alignItems: 'center' ,height: '100%'}}>
                <VideoCameraOutlined style={{ fontSize: '20px', marginRight: '8px' }} />
                <span>视频上传</span>
              </div>
            }
            bordered={false}
            style={{ borderRadius: '15px', boxShadow: '0 4px 12px rgba(0,0,0,0.05)' ,height: '970px'}}
          >
            <Row gutter={24}>
              <Col span={12} style={{ 
                display: 'flex', 
                flexDirection: 'column', 
                alignItems: 'center', 
                justifyContent: 'center', 
                borderRight: '2px solid #f0f0f0', 
                paddingRight: '20px',
                minHeight: '400px'
              }}>
                <div style={{ 
                  width: '100%', 
                  padding: '40px', 
                  backgroundColor: '#fafafa', 
                  borderRadius: '10px',
                  textAlign: 'center'
                }}>
                  <Upload
                    multiple
                    onRemove={handleRemove}
                    beforeUpload={handleBeforeUpload}
                    fileList={fileList}
                    style={{ width: '100%' }}
                  >
                    <Button  type="dashed" style={{ 
                      width: '100%', 
                      height: '120px',
                      fontSize: '16px',
                      borderStyle: 'dashed',
                      borderRadius: '10px',
                      display: 'flex',
                      flexDirection: 'column',
                      justifyContent: 'center',
                      alignItems: 'center',
                      gap: '10px'
                    }}>
                      <UploadOutlined style={{ fontSize: '32px' }} />
                      <span>点击或拖拽视频文件到此处</span>
                    </Button>
                  </Upload>
                  <Button
                    type="primary"
                    onClick={handleUpload}
                    disabled={fileList.length === 0 || uploading}
                    loading={uploading}
                    style={{ 
                      width: '50%', 
                      height: '40px',
                      fontSize: '16px', 
                      marginTop: '20px',
                      borderRadius: '20px'
                    }}
                  >
                    {uploading ? '上传中...' : '开始上传'}
                  </Button>
                </div>
              </Col>
              <Col span={12}>
                {fileList.map((file) => (
                  <Card key={file.uid} style={{ marginBottom: '20px', borderRadius: '10px' }}>
                    <Input
                      placeholder="输入视频名字"
                      value={file.name}
                      style={{ marginBottom: '10px', borderRadius: '6px' }}
                    />
                    <video 
                      src={videoPreviews[file.uid]} 
                      controls 
                      style={{ 
                        width: '100%', 
                        marginTop: '10px',
                        borderRadius: '8px',
                        backgroundColor: '#000'
                      }} 
                    />
                    <Progress 
                      percent={progress[file.name] || 0} 
                      status="active" 
                      strokeColor={{
                        '0%': '#108ee9',
                        '100%': '#87d068',
                      }}
                      style={{ marginTop: '10px' }}
                    />
                  </Card>
                ))}
              </Col>
            </Row>
          </Card>
        ) : (
          <Card
            title={
              <div style={{ display: 'flex', alignItems: 'center' }}>
                <HistoryOutlined style={{ fontSize: '20px', marginRight: '8px' }} />
                <span>上传记录</span>
              </div>
            }
            bordered={false}
            style={{ borderRadius: '15px', boxShadow: '0 4px 12px rgba(0,0,0,0.05)' }}
          >
            {loading ? (
              <div style={{ textAlign: 'center', padding: '40px' }}>
                <Spin size="large" />
              </div>
            ) : (
              <div style={{ 
                display: 'grid', 
                gridTemplateColumns: 'repeat(auto-fill, minmax(300px, 1fr))', 
                gap: '20px',
                padding: '20px'
              }}>
                {uploadedFiles.map((fileName, index) => (
                  <Card
                    key={index}
                    hoverable
                    style={{ borderRadius: '10px', overflow: 'hidden' }}
                  >
                    <div style={{ textAlign: 'center' }}>
                      <Typography.Text strong style={{ fontSize: '16px' }}>
                        {fileName}
                      </Typography.Text>
                      <video
                        src={generateSignedUrl(fileName)}
                        controls
                        style={{ 
                          width: '100%', 
                          marginTop: '10px',
                          borderRadius: '8px',
                          backgroundColor: '#000'
                        }}
                      />
                    </div>
                  </Card>
                ))}
              </div>
            )}
          </Card>
        )}
      </div>
    </div>
  );
};

export default Publish;